#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
--------------------------------------
"""
__author__ = 'JiChao_Song'
__data__ = '2020/5/31 下午9:47'

from django.core.paginator import Paginator
from django.utils.datastructures import MultiValueDictKeyError
from rest_framework.exceptions import ValidationError, ParseError
from rest_framework.generics import GenericAPIView

from common.utils.request import JsonMessage, PageResponse


class ViewModel:
    Model = None
    # 定义需要查询的字段列表
    """
    模糊查询字段示例: fields__icontains  fields为字段名
    """
    Search_fields = []


class InfoModel(GenericAPIView, ViewModel):
    """
    详情
    """

    def post(self, request, *args, **kwargs):
        try:
            id = request.data['id']
            if id is None or id == "":
                return JsonMessage(message="接口id不能为空", code=40001).jsonExit()
            else:
                queryset = self.Model.objects.filter(id=id)
                serializer = self.serializer_class(queryset, many=True)
                return JsonMessage(data=serializer.data).jsonExit()

        except ValidationError as e:

            return JsonMessage(code=40000, message="数据校验错误", errors=e.detail).jsonExit()

        except KeyError as e:
            return JsonMessage(code=40001, message="参数错误").jsonExit()

        except MultiValueDictKeyError as e:

            return JsonMessage(code=40002, message="%s不能为空" % str(e)).jsonExit()

        except ParseError as e:

            return JsonMessage(code=40003, message="参数解析错误", errors=e.detail).jsonExit()

        except Exception as e:

            return JsonMessage(code=50000, message="系统异常", errors=str(e)).jsonExit()


class ListModel(GenericAPIView, ViewModel):
    """
    列表
    """

    def post(self, request, *args, **kwargs):

        try:
            params_list = list(request.data.keys())
            params_dict = {}
            if len(self.Search_fields) != 0:
                for param in self.Search_fields:
                    if param in params_list and request.data[param] is not None:
                        params_dict[param] = request.data[param]

            if len(params_dict.keys()) == 0:
                get_queryset = self.Model.objects.all()
            else:
                get_queryset = self.Model.objects.filter(**params_dict)

            if 'page' in params_list:
                page = request.data['page']
                if page is None or page == "":
                    page = 1
            else:
                page = 1
            if 'size' in params_list:
                size = request.data['size']
                if size is None or size == "":
                    size = len(get_queryset)
            else:
                size = len(get_queryset)
            ptr = Paginator(get_queryset.order_by('-id'), size)
            data = ptr.page(page)
            serializer = self.serializer_class(data, many=True)
            return PageResponse(total=ptr.count, page=page, size=size, data=serializer.data).jsonExit()

        except ValidationError as e:

            return JsonMessage(code=40000, message="数据校验错误", errors=e.detail).jsonExit()

        except KeyError as e:
            return JsonMessage(code=40001, message="参数错误").jsonExit()

        except MultiValueDictKeyError as e:

            return JsonMessage(code=40002, message="%s不能为空" % str(e)).jsonExit()

        except ParseError as e:

            return JsonMessage(code=40003, message="参数解析错误", errors=e.detail).jsonExit()

        except Exception as e:

            return JsonMessage(code=50000, message="系统异常", errors=str(e)).jsonExit()


class AddModel(GenericAPIView, ViewModel):
    """
    创建
    """

    def post(self, request, *args, **kwargs):
        try:

            serializer = self.get_serializer(data=request.data)

            serializer.is_valid(raise_exception=True)

            serializer.save()

            return JsonMessage(data=serializer.data, message='创建成功', code=20000).jsonExit()

        except ValidationError as e:
            return JsonMessage(code=40000, message="数据校验错误", errors=e.detail).jsonExit()

        except KeyError as e:
            return JsonMessage(code=40001, message="参数错误").jsonExit()

        except MultiValueDictKeyError as e:

            return JsonMessage(code=40002, message="%s不能为空" % str(e)).jsonExit()

        except ParseError as e:

            return JsonMessage(code=40003, message="参数解析错误", errors=e.detail).jsonExit()

        except Exception as e:
            print(type(e))

            return JsonMessage(code=50000, message="系统异常", errors=str(e)).jsonExit()


class EditModel(GenericAPIView, ViewModel):
    """
    修改
    """

    def post(self, request, *args, **kwargs):

        try:
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            message = "修改成功"
            return JsonMessage(message=message).jsonExit()

        except ValidationError as e:
            return JsonMessage(code=40000, message="数据校验错误", errors=e.detail).jsonExit()

        except KeyError as e:
            return JsonMessage(code=40001, message="参数错误").jsonExit()

        except MultiValueDictKeyError as e:

            return JsonMessage(code=40002, message="%s不能为空" % str(e)).jsonExit()

        except ParseError as e:

            return JsonMessage(code=40003, message="参数解析错误", errors=e.detail).jsonExit()

        except Exception as e:

            return JsonMessage(code=50000, message="系统异常", errors=str(e)).jsonExit()


class DeleteModel(GenericAPIView, ViewModel):
    """
    删除
    """

    def post(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
            instance.delete()
            message = "删除成功"
            return JsonMessage(message=message).jsonExit()

        except ValidationError as e:
            return JsonMessage(code=40000, message="数据校验错误", errors=e.detail).jsonExit()

        except KeyError as e:
            return JsonMessage(code=40001, message="参数错误").jsonExit()

        except MultiValueDictKeyError as e:

            return JsonMessage(code=40002, message="%s不能为空" % str(e)).jsonExit()

        except ParseError as e:

            return JsonMessage(code=40003, message="参数解析错误", errors=e.detail).jsonExit()

        except Exception as e:

            return JsonMessage(code=50000, message="系统异常", errors=str(e)).jsonExit()


class ApiModel(ListModel, AddModel, EditModel, DeleteModel):
    pass
